package com.kaili.controller.web.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.util.FreemarkUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.db.service.IHsEwbsDispatchService;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.pojo.dto.dispatch.DispatchAddDTO;
import com.kaili.pojo.dto.dispatch.DispatchQueryDTO;
import com.kaili.pojo.vo.DispatchRouteVO;
import com.kaili.pojo.vo.DispatchVO;
import com.kaili.pojo.vo.EwbDispatchVO;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.*;

/**
 * @AUTHOR pengdongxu.
 * @Date: 18-5-25 上午9:13.
 * @COPYRIGHT 杭州凯立
 */

@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Validated
@Api(tags = "到件派送", description = "到件送货相关API")
public class ArriveSendController {

    @Autowired
    private IHsEwbsDispatchService dispatchService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private UserFeignClient userFeignClient;

    @ApiOperation(value = "获取未分配派送托运单")
    @GetMapping("/dispatchs/undistributed")
    public List<EwbDispatchVO> queryEwbUnsendList(@Validated @ModelAttribute DispatchQueryDTO req){
        Map<Object, Object> search = new HashMap<>();
        search.putAll(new org.apache.commons.beanutils.BeanMap(req));
        search.put("pickGoodsModeId",105);//派送
        List<EwbDispatchVO> ewbDispatchVOS = dispatchService.queryUndispatchEwbList(search);
        List<EwbDispatchVO> ewbDispatchVOList = new ArrayList<>();
        for (EwbDispatchVO ewbDispatchVO : ewbDispatchVOS){
            if (ewbDispatchVO != null && Objects.equals(ewbDispatchVO.getOutPiece(), ewbDispatchVO.getPiece())
                    && Objects.equals(ewbDispatchVO.getOutPiece(), ewbDispatchVO.getEwbPiece())){
                ewbDispatchVOList.add(ewbDispatchVO);
            }
        }
        return ewbDispatchVOList;
    }

    @ApiOperation(value = "根据送货单号获取送货单的所有运单信息")
    @GetMapping("/dispatchs/{operationId}/queryEwbByDispatchNo")
    public List<EwbDispatchVO> queryEwbByDispatchNo(@Pattern(regexp = "^[A-Za-z0-9]{0,20}$",message = "派送单应为[A-Za-z0-9]组成的1-20位字符")
                                                        @PathVariable("operationId") String operationId, @NotNull(message = "标记不能为空") @RequestParam("flag") Integer flag){
        if (!StringUtils.isEmpty(operationId)){
            Map<String, Object> search = new HashMap<>();
            search.put("operationId",operationId);
            //search.put("siteId",login.getLoginSiteId());
            List<EwbDispatchVO> page = dispatchService.getEwbInfoByDispatchNo(search);
            if(flag==1){
                for(EwbDispatchVO ewbDispatchVO:page){
                    if(ewbDispatchVO.getIsSign()==1){
                        throw new BaseExcept(ResponseStatus.IS_SIGN);
                    }
                }
            }
            return page;
        }
        throw new BaseExcept(ResponseStatus.DISPATCH_QUERY_ERR);
    }

    @ApiOperation(value = "修改派送")
    @PutMapping("/dispatchs/{operationId}")
    public Map<String, String> updateDispatch(@Validated @RequestBody DispatchAddDTO dispatchAddDTO){
        return dispatchService.addDispatchBS(dispatchAddDTO);
    }

    @ApiOperation(value = "到件派送删除")
    @DeleteMapping("/dispatchs/{operationId}")
    public ResponseStatus deleteDispatch(@Pattern(regexp = "^[A-Za-z0-9]{0,20}$",message = "派送单应为[A-Za-z0-9]组成的1-20位字符")
                                                @PathVariable("operationId")String operationId){
        Map<String, Object> search = new HashMap<>();
        search.put("operationId",operationId);
        List<EwbDispatchVO> page = dispatchService.getEwbInfoByDispatchNo(search);
        for(EwbDispatchVO ewbDispatchVO:page){
            if(ewbDispatchVO.getIsSign()==1){
               return  ResponseStatus.IS_DELETE;
            }
        }
        if (0<= dispatchService.deleteDispatchByEwbNo(operationId)){
            return ResponseStatus.RESPONSE_OK;
        }else {
            throw new BaseExcept(ResponseStatus.DISPATCH_DELETE_ERR);
        }

    }

    @ApiOperation(value = "获取派件的地址")
    @GetMapping(value = "/dispatchs/routeList")
    public List<DispatchRouteVO> queryDispatchRouteList(@Validated @ModelAttribute DispatchQueryDTO request){
    return dispatchService.queryDispatchRouteList(request.getSearch());
    }

    @GetMapping("/dispatchs/html")
    @ApiOperation(value = "到货派送打印")
    public String queryArrivalPrint(@RequestParam("arrivalNo") @ApiParam(value="派送单号逗号连接字符串",defaultValue = "0000011111") String arrivalNo) throws BaseExcept {
        if(StringUtils.isEmpty(arrivalNo)){
            throw new BaseExcept(ResponseStatus.PRINT_NULL);
        }
        String logo = userFeignClient.getCompanyLogo(Long.parseLong(LoginDetailUtils.getCompanyCode()));
        JSONObject json= JSON.parseObject(logo);
        List<String> arrivalList = Arrays.asList(arrivalNo.split(","));
        Map parm = new HashMap();
        parm.put("arrivalList",arrivalList);
        List<DispatchVO> list=dispatchService.queryArrivalNoList(parm);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DispatchVO bean = list.get(i);
                Map searchMap = new HashMap();
                searchMap.put("operationId", bean.getOperationId());
                bean.setEwbDispatchVOList( dispatchService.getEwbInfoByDispatchNo(searchMap));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("companyName", LoginDetailUtils.getCompanyName());
        if(StringUtils.isEmpty(String.valueOf(json.get("data")))){
            map.put("pictureUrl","../api/static/logo.png");
        }else {
            map.put("pictureUrl", json.get("data"));
        }
        return FreemarkUtils.getPrintTemplate(configuration,"arrivalNo", map);
    }

}
